<template>
  <view class="page page-grey has-fixed-footer page-activity-goods">
    <view class="page-fixed-placeholder"></view>
    <view class="page-fixed-top">
      <view class="page-search">
        <fui-input v-model="searchValue" borderTop color="#333" radius=16 :borderBottom="false" placeholderStyle="font-size:28rpx" placeholder="请输入商品名称搜索"></fui-input>
        <span class="icon iconfont">&#xe628;</span>
      </view>
      <view class="filter-wrapper" v-show="filterGoodsList.length && !searchValue">
        <view class="filter-item" :class="{'active': isCheckAll}" @click="handleCheckAll">全选</view>
      </view>
    </view>
    <view class="goods-list" :class="{'no-filter': searchValue}" v-show="filterGoodsList.length">
      <view class="goods-item" v-for="item in filterGoodsList" :key="item.id + ''" @click="handleCheckItem(item.id + '')">
        <view class="goods-item-check">
          <fui-icon name="checkbox-fill" v-if="checkedGoodsIds.indexOf(item.id + '') > -1" size="40" color="var(--fui-color-primary)"></fui-icon>
          <fui-icon name="checkround" v-else size="40" color="#ccc"></fui-icon>
        </view>
        <image :src="item.sliderPicUrls[0]" style="width: 164rpx; height: 164rpx; border-radius: 16rpx; overflow: hidden;" mode=""></image>
        <view class="goods-item-right">
          <view class="right-title">{{item.name}}</view>
          <view class="right-list">
            <view class="right-text">
              <image src="/static/images/icon-kc.png" style="width: 22rpx; height: 22rpx;"></image>
              库存 <span class="right-number">{{item.stock}}</span><span>{{item.unit}}</span>
            </view>
            <view class="right-text">
              <image src="/static/images/iocn-dj.png" style="width: 26rpx; height: 26rpx;"></image>
              单价 <span class="right-number">{{ utils.moneyFormatter(item.price / 100)}}</span><span>元/{{item.unit}}</span>
            </view>
            <view class="right-text">
              <image src="/static/images/icon-qssl.png" style="width: 24rpx; height: 22rpx;"></image>
              起售数量 <span class="right-number">{{item.startNum}}</span><span>{{item.unit}}</span>
            </view>
          </view>
        </view>
      </view>
    </view>
    <fui-empty v-show="!filterGoodsList.length" :isFixed="true" src="/static/images/empty/data.png" title="暂无可选商品" size="24" color="#999"></fui-empty>
    <view class="ui-fixed-footer ui-fixed-footer__white">
      <fui-button class="ui-btn-primary_plain" text="取消" height="78rpx" radius="8rpx" :margin="['0', '54rpx', '0', '0']" @click="tab.navigateBack"></fui-button>
      <fui-button text="确定" height="78rpx" radius="8rpx" :margin="['0']" @click="handleSubmit"></fui-button>
    </view>
  </view>
</template>

<script setup>
import { ref, reactive, computed, inject } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { useStore } from 'vuex'
import utils from '@/components/firstui/fui-utils'
import activityApi from '@/api/activity/joinin'

const store = useStore()
const tab = inject('$tab')
const modal = inject('$modal')

const activityId = ref('')
const recordId = ref('')
const productSpuIds = ref('')
const goodsList = ref([])

onLoad(async option => {
  activityId.value = option.activityId || ''
  recordId.value = option.recordId || ''
  productSpuIds.value = option.productSpuIds || ''
  await getGoodsList()
  isCheckAll.value = checkedGoodsIds.value.length === goodsList.value.length
})

// 搜索
const searchValue = ref('')
const filterGoodsList = computed(() => {
  return goodsList.value.filter(item => item.name.indexOf(searchValue.value) > -1)
})

// 单选
const isCheckAll = ref(false)
const checkedGoodsIds = ref([])
const handleCheckItem = (id) => {
  const itemIndex = checkedGoodsIds.value.indexOf(id)
  if (itemIndex > -1) {
    checkedGoodsIds.value.splice(itemIndex, 1)
  } else {
    checkedGoodsIds.value.push(id)
  }
  isCheckAll.value = checkedGoodsIds.value.length === goodsList.value.length
}

// 全选
const handleCheckAll = async () => {
  isCheckAll.value = await !isCheckAll.value
  if (isCheckAll.value) {
    checkedGoodsIds.value = goodsList.value.map(item => item.id + '')
  } else {
    checkedGoodsIds.value = []
  }
}

// 保存
const handleSubmit = () => {
  if (!checkedGoodsIds.value.length) {
    modal.msgError('请至少选择一个商品！')
    return
  }

  if (recordId.value) {
    activityApi.updateActivityGoods({
      id: recordId.value,
      productSpuIds: productSpuIds.value ? `${productSpuIds.value},${checkedGoodsIds.value.join(',')}` : checkedGoodsIds.value.join(',')
    }).then(res => {
      if (res.code === 0) {
        modal.msg('商品已添加！')
        setTimeout(() => {
          tab.navigateBack()
        }, 1000)
      } else {
        modal.msg('添加失败！')
      }
    }).catch(err => {
      modal.msg(err.msg || err || '添加失败！')
    })
  } else {
    activityApi.submitActivityGoods({
      supplierId: store.getters.companyId,
      activityId: activityId.value,
      productSpuIds: checkedGoodsIds.value.join(',')
    }).then(res => {
      if (res.code === 0) {
        modal.msg('报名成功！')
        setTimeout(() => {
          tab.navigateBack()
        }, 1000)
      } else {
        modal.msg('报名失败！')
      }
    }).catch(err => {
      modal.msg(err.msg || err || '报名失败！')
    })
  }
}

// 可选商品
const getGoodsList = async () => {
  modal.loading('加载中...')
  try {
    await activityApi.getCheckGoodsList({
      supplierId: store.getters.companyId,
      activityId: activityId.value,
      name: searchValue.value
    }).then((res) => {
      if (res.code === 0){
        goodsList.value = res.data || []
        modal.closeLoading()
      } else {
        modal.msgError(res.msg)
      }
    })
  } catch(e){
    modal.closeLoading()
    modal.msgError(e.msg)
  }
}
</script>

<style lang="scss" scoped>
.page-activity-goods {
  padding: 36rpx 36rpx 186rpx;
  .page-fixed-placeholder {
    position: fixed;
    z-index: 9;
    top: 0;
    left: 0;
    right: 0;
    height: 200rpx;
    background-color: #f8f8f8;
  }
  .page-fixed-top {
    position: fixed;
    z-index: 10;
    left: 36rpx;
    right: 36rpx;
    background-color: #f8f8f8;
    .page-search {
      :deep(.fui-input__wrap) {
        padding: 20rpx 24rpx !important;
      }

      span {
        position: absolute;
        z-index: 10;
        right: 0;
        top: 0;
        font-size: 1.25rem;
        color: var(--fui-color-link);
        display: inline-block;
        width: 40px;
        height: 40px;
        line-height: 40px;
        text-align: center;
        font-size: 40rpx;
        color: var(--fui-color-link);
      }
    }
    
    .filter-wrapper {
      display: flex;
      background: #ffffff;
      border-top-left-radius: 16rpx;
      border-top-right-radius: 16rpx;
      margin-top: 24rpx;
      padding: 28rpx !important;
      .filter-item {
        border-radius: 24rpx;
        background-color: #f5f7fe;
        line-height: 48rpx;
        margin-right: 24rpx;
        padding: 0 32rpx;
        font-size: 24rpx;
        &.active {
          background-color: var(--fui-color-primary);
          color: #fff;
        }
      }
    }
  }
  .goods-list {
    background: #ffffff;
    border-radius: 16rpx;
    padding: 28rpx 28rpx 0 !important;
    box-sizing: border-box;
    margin-top: 164rpx;
    &.no-filter {
      margin-top: 108rpx;
    }
    .goods-item {
      display: flex;
      align-items: center;
      width: 100%;
      background: #ffffff;
      border-radius: 16rpx;
      padding: 28rpx !important;
      box-sizing: border-box;
      &:not(:last-child) {
        border-bottom: 2rpx solid #f1f1f1;
      }

      .goods-item-check {
        position: relative;
        margin-right: 24rpx;
        ::v-deep .fui-checkbox__input {
          position: absolute;
          z-index: 99;
          top: 28rpx;
          transform: translateY(-50%) !important;
          width: 100%;
          height: 164rpx;
          border-radius: 0 !important;
          margin-right: 24rpx;
          opacity: 0;
        }
      }

      .goods-item-right {
        margin-left: 24rpx;
        width: calc(100% - 188rpx);
        .right-title {
          font-size: 28rpx;
          font-weight: bold;
          color: #333333;
          margin-bottom: 16rpx;
        }
        .right-list {
          display: flex;
          flex-wrap: wrap;
          .right-text {
            width: 100%;
            font-size: 24rpx;
            font-weight: 400;
            color: #999999;
            display: flex;
            align-items: center;
            margin-bottom: 10rpx;

            image {
              padding-right: 10rpx;
            }

            span {
              color: #333333;
            }
            .right-number {
              font-weight: bold;
              color: #2c83fc;
              padding: 0 10rpx;
            }
          }
        }
      }
    }
  }
  .ui-fixed-footer {
    display: flex;
  }
}
</style>